import dataPreferences from '@ohos.data.preferences';
import UIAbility from '@ohos.app.ability.UIAbility';

/**
 * app 公共数据存储类
 */
class SP {

  //首选项Key字段
  private KEY_APP_FONT_SIZE = 'advert';
  private KEY_APP_STARTUP_COUNT = 'appStartupCount';

  createAppSP(context) {
    // 首选项名字
    const PREFERENCES_NAME = 'defSP';
    globalThis.getFontPreferences = (() => {
      // 获取首选项实例
      let preferences: Promise<dataPreferences.Preferences> = dataPreferences.getPreferences(context, PREFERENCES_NAME);
      return preferences;
    });
  }

  async getAppStartupCount() {
    let appStartupCount: number = 0;
    const preferences = await globalThis.getFontPreferences();
    appStartupCount = await preferences.get(this.KEY_APP_STARTUP_COUNT, appStartupCount);
    return appStartupCount;
  }

  saveAppStartupCount(fontSize: number) {
    globalThis.getFontPreferences().then((preferences) => {
      // 判断保存的key是否存在
      preferences.has(this.KEY_APP_STARTUP_COUNT).then(async (isExist) => {
        // Logger.info(TAG, 'preferences has changeFontSize is ' + isExist);
        if (!isExist) {
          // 保存数据
          await preferences.put(this.KEY_APP_STARTUP_COUNT, fontSize);
          preferences.flush();
        }
      }).catch((err) => {
        // Logger.error(TAG, 'Has the value failed with err: ' + err);
      });
    }).catch((err) => {
      // Logger.error(TAG, 'Get the preferences failed, err: ' + err);
    });
  }


  // createAppStartupCount(context) {
  //   // 首选项名字
  //   const PREFERENCES_NAME = 'appStartupCount';
  //   globalThis.getFontPreferences = (() => {
  //     // 获取首选项实例
  //     let preferences: Promise<dataPreferences.Preferences> = dataPreferences.getPreferences(context, PREFERENCES_NAME);
  //     return preferences;
  //   });
  // }
  //
  // createAdvert(context) {
  //   // 首选项名字
  //   const PREFERENCES_NAME = 'advert';
  //   globalThis.getFontPreferences = (() => {
  //     // 获取首选项实例
  //     let preferences: Promise<dataPreferences.Preferences> = dataPreferences.getPreferences(context, PREFERENCES_NAME);
  //     return preferences;
  //   });
  // }
  //
  // async getChangeFontSize() {
  //   let fontSize: number = 0;
  //   const preferences = await globalThis.getFontPreferences();
  //   fontSize = await preferences.get(this.KEY_APP_FONT_SIZE, fontSize);
  //   return fontSize;
  // }

}

export default new SP()